<template>
	<!-- 此页面只有现金与充值劵 -->
	<view class="p30">
		<view class="one">
			<view class="oneTitle">
				可领取优惠券：
			</view>
			<u-table class="tables">
				<u-tr class="u-tr ">
					<u-th class="u-th trth zz">优惠券名称</u-th>
					<u-th class="u-th trth ww">面额(元)</u-th>
					<u-th class="u-th trth ss">类型</u-th>
					<u-th class="u-th trth qq">领劵限制</u-th>
					<u-th class="u-th trth ss">操作</u-th>
				</u-tr>
				<u-tr class="u-tr" v-for="(item,index) in initList" :key="index">
					<block class="">
						<view class="" v-if="item.couponType !== 3 && item.couponType !== 1"
							style="display: flex;justify-content: space-around;align-items: center;min-height: 98upx;margin-bottom: 10upx;width: 100%;">
							<u-td class="zz">{{item.couponName}}</u-td>
							<u-td class="ww">{{item.couponType == 1 ? item.holdDays + '天' : item.discount + '元'  }}
							</u-td>
							<u-td class="ss">
								{{item.couponType == 0 ? '充值劵' : item.couponType == 1 ? '暂存劵' : item.couponType == 2 ? '代金券' : item.couponType == 3 ? '试用劵' : item.couponType == 4 ? '套餐抵扣劵' :  '--' }}
							</u-td>
							<u-td class="qq">
								{{item.couponLimit == 0 ? '无限量' : item.couponLimit == 1 ? '限一张' : '--' }}
							</u-td>

							<u-td class="ss"><text class="green" @click="getlingquFn(item)">领取</text>
							</u-td>
						</view>
					</block>
				</u-tr>
				<u-tr v-if="!isOne" class="u-tr ">
					<u-td class="u-td">暂无数据</u-td>
				</u-tr>
			</u-table>
		</view>
		<view class="two" style="margin-bottom: 60upx;">
			<view class="oneTitle twoTitle">
				已领取优惠券：
			</view>
			<u-table class="tables">
				<u-tr class="u-tr ">
					<u-th class="u-th twoTrth zz">优惠券名称</u-th>
					<u-th class="u-th twoTrth xx">面额(元)</u-th>
					<u-th class="u-th twoTrth xx">类型</u-th>
					<u-th class="u-th twoTrth xx">操作</u-th>
				</u-tr>

				<u-tr class="u-tr" v-for="i in idList" :key="i.id">
					<block>
						<view class="" v-if="item.couponType !== 3 && item.couponType !== 1"
							style="display: flex;justify-content: space-around;align-items: center;border: 0.5upx solid #eee;min-height: 98upx;margin-bottom: 10upx;width: 100%;">
							<u-td class="zz">{{i.couponName}}</u-td>
							<u-td class="xx">{{i.couponType == 1 ? i.holdDays + '天' : i.discount + '元'  }}</u-td>
							<u-td class="xx">
								<text
									:class="i.couponType == 0 ? 'greens' : i.couponType == 1 ? 'reds' : i.couponType == 2 ? 'blues' : i.couponType == 3 ? 'blues' :  i.couponType == 4 ? 'qing' : ''">{{i.couponType == 0 ? '充值劵' : i.couponType == 1 ? '暂存劵' : i.couponType == 2 ? '代金券' :i.couponType == 3 ? '试用劵' : i.couponType == 4 ? '套餐抵扣劵': '--' }}</text>

							</u-td>
							<u-td class="xx">
								<!-- <text v-if="i.couponType == 0">{{'满' + i.useCondition + '可用' + i.discount + '元'}}</text> -->
								<text v-if="i.couponType !== 1" class="green" @click="varRouter(i)">使用</text>
								<!-- <text v-if="i.couponType == 1" class="green"
								@click="varRouter(i)">购买套餐</text> -->
							</u-td>
						</view>
					</block>
				</u-tr>

				<u-tr v-if="!isTwo" class="u-tr ">
					<u-td class="u-td">暂无数据</u-td>
				</u-tr>
			</u-table>
		</view>
		<view v-if="isNew" class="two" style="margin-top: 50upx;margin-bottom: 80upx;">
			<view class="oneTitle threeTitle">
				新人优惠券：
			</view>
			<u-table class="tables">
				<u-tr class="u-tr ">
					<u-th class="u-th twoTrth zz">优惠券名称</u-th>
					<u-th class="u-th twoTrth">面额(元)</u-th>
					<u-th class="u-th twoTrth aa">使用限制</u-th>
				</u-tr>
				<u-tr v-if="isTwo" class="u-tr" v-for="i in newList" :key="i.id">
					<u-td class="u-td zz">{{i.name}}</u-td>
					<u-td class="u-td">{{i.couponType !== 1 ? i.discount : i.holdDays + '天'}}</u-td>

					<u-td class="u-td aa"> {{'满' + i.useCondition + '可用' + i.discount + '元'}}
					</u-td>
				</u-tr>
			</u-table>
		</view>
		<!-- 归还电池 -->
		<!-- 	<view style="margin-top: 15%;" class="plr100 mb30">
			<view>
				<u-button type="primary" shape="circle" @click="returnTheBatteryFn">归还电池</u-button>
			</view>
			<view style="margin-top: 5%;text-align: center;">使用暂存卷之前先归还电池</view>
		</view> -->



		<!-- 使用暂存卷信息 start -->
		<view>
			<u-modal v-model="cashShow" title="暂存劵使用" :title-style="{color: 'red'}" :mask-close-able="true"
				confirm-text="确认使用" :zoom="true" :show-cancel-button="true" @confirm="cashConfirm"
				:content="cashContent">
			</u-modal>
		</view>
		<view>
			<u-modal v-model="isShow" title="你现有的套餐信息" :title-style="{color: 'red'}" :mask-close-able="true"
				:zoom="true" :show-confirm-button="false" :content="isContent">
			</u-modal>
		</view>
		<!-- 使用暂存卷信息 end -->

	</view>
</template>
<script>
	import {
		mapState
	} from 'vuex'
	import {
		couponListByUser,
		couponGetUserCoupon,
		APIreceive,
		operatorGetGiveInfo,
		couponHoldCoupon,
		scanDevice,
		deviceReturnOpenDoor,
		getMyMeal
	} from '@/api/user.js'
	export default {
		name: 'rentElePackage',
		data() {
			return {
				initList: [],
				idList: [],
				newList: [],
				isTwo: false,
				isOne: false,
				isNew: false,
				cashShow: false,
				isShow: false,
				cashContent: '',
				isContent: '',
				temporaryObj: {},
				query: {},
				info: {},
				// mealState: '',
				isMealState: false,
				zdeviceId: '',
				deviceNo: '',
				agentId: '',
				isTapScan: false, // 是否可以正常扫码 （阻止用户同一时间点，多次点击）

			}
		},

		onLoad(e) {
			this.zdeviceId = e.deviceId || ''
			console.log('3333333', e);
		},
		onShow() {
			this.info = uni.getStorageSync('oneData') || {}
			this.agentId = uni.getStorageSync('oneData').agentId || ''
			this.deviceNo = uni.getStorageSync('oneData').deviceNo || ''
			this.zdeviceId = uni.getStorageSync('oneData').deviceId || ''
			this.query = uni.getStorageSync('query') || {}
			this.init()
		},
		methods: {
			// 扫码
			returnTheBatteryFn() {
				// 防抖
				if (this.isTapScan) {
					return false
				}
				this.isTapScan = true
				setTimeout(() => {
					this.isTapScan = false
				}, 2000)
				const _self = this
				// 调起扫码接口
				uni.scanCode({
					scanType: ['barCode', 'qrCode'], //扫码类型
					// 扫码成功
					async success(res) {
						if (res.errMsg == 'scanCode:ok') {
							let deviceNo = ''
							let deviceType = 0
							if (res.scanType == 'QR_CODE') { //扫的码是二维码类型
								// http://weixin.qq.com/r/test?deviceNo=131211&deviceType=1
								// deviceType设备类型 1:换电柜 2：租车 3：充电柜
								// 获取路由url的参数值
								deviceNo = _self.getUrlParam('deviceNo', res.result)
								deviceType = _self.getUrlParam('deviceType', res.result)
								if (deviceType == 2 || deviceType == 3) {
									_self.toast('请扫描正确的二维码！')
									return false
								}
								_self.$store.commit('scanCode', deviceType)
								if (deviceNo) {
									console.log('=======', deviceType, deviceNo);
									const resss = await deviceReturnOpenDoor({
										deviceNo: deviceNo,
										handlerType: 3, //3寄存电池 4押金退还电池
									})
									console.log('resss', resss);
									if (resss.code === 200) {
										console.log('归还成功');
									} else {
										_self.toast(resss.msg || '归还失败')
									}


								} else {
									_self.toast('扫码失败')
								}
							} else {
								_self.toast('请扫正确的二维码')
							}
						}
					},
					// 扫码失败
					fail(err) {
						_self.toast('扫码失败')
					}
				})
			},

			// 使用暂存劵11
			async cashConfirm() {
				const res = await couponHoldCoupon({
					couponUserId: this.temporaryObj.id || '',
					agentId: this.agentId,
				})
				this.toast(res.code == 200 ? '使用成功' : res.msg)

				setTimeout(async () => {
					await this.init()
				}, 1500)

				if (res.code == 200) {
					setTimeout(async () => {
						this.isShow = true;
						const ress = await scanDevice(this.query)
						uni.setStorageSync('oneData', ress.data)
						this.info = ress.data
						let infos = ress.data || {}
						this.isContent = `
							总换电次数：${infos.nums}次 <br>
							剩余换电次数：${infos.num}次 <br>
							套餐结束时间：${infos.validityTime} <br>
							套餐电池类型：${infos.btType}V <br>
						`
					}, 2000)
				}
			},

			async init() {
				const res = await couponListByUser(this.agentId)
				let list = res.data || []
				this.initList = []
				if (list.lenth !== 0) {
					list.forEach((i) => {
						if (i.couponType !== 1 && i.couponType !== 3) {
							this.initList.push(i)
						}
					})
				} else {
					this.initList = []
				}
				const ress = await couponGetUserCoupon({
					agentId: this.agentId
				})

				let lists = ress.data || []
				this.idList = []
				if (lists.lenth !== 0) {
					lists.forEach((i) => {
						if (i.couponType !== 1 && i.couponType !== 3) {
							this.idList.push(i)
						}
					})

				} else {
					this.idList = []
				}
				if (this.initList.length === 0) {
					console.log('46464', this.initList);
					this.isOne = false
				} else {
					console.log('888888', this.initList);
					this.isOne = true
				}
				if (this.idList.length === 0) {
					this.isTwo = false
				} else {
					this.isTwo = true
				}

			},
			async varRouter(i) {
				const getss = await getMyMeal({
					deviceId: this.zdeviceId
				})
				// if (!getss.data) {
				// 	this.toast('请先购买套餐再使用')
				// 	return false
				// }
				//优惠券类型,0充值券,1暂存券,2代金券,3试用劵  4套餐抵扣劵
				if (i.couponType == 0) {
					console.log('这是000000');
					await this.routerLink({
						path: '/pages/user/wallet/recharge'
					})
				}
				if (i.couponType == 1) {
					if (this.isMealState) {
						this.temporaryObj = i
						this.cashContent = `你使用该暂存劵，来延迟你的套餐时间？<br>
					以下是你现拥有的套餐信息：<br>
					总换电次数：${this.info.nums}次 <br>
						剩余换电次数：${this.info.num}次 <br>
						套餐结束时间：${this.info.validityTime} <br>
						套餐电池类型：${this.info.btType}V <br>
					`
						this.cashShow = true;
					} else {

						this.routerLink({
							path: '/pages/user/rentEle/package',
							query: {
								// type: 2,
								deviceId: this.zdeviceId,

							}
						})
					}

				}
				if (i.couponType == 2) {
					// await this.routerLink({
					// 	path: '/pages/user/wallet/index'
					// })
					uni.reLaunch({
						url: `/pages/user/wallet/index?cash=${i.discount}&couponId=${i.id}&agentId=${i.agentId}`,
					});
				}
				if (i.couponType == 3) {
					console.log('333这是3');
					this.routerLink({
						path: '/pages/user/rentEle/package',
						query: {
							// type: 2,
							deviceId: this.zdeviceId,

						}
					})
				}
				if (i.couponType == 4) {
					// console.log('4444这是4', i);
					this.routerLink({
						path: '/pages/user/rentEle/package',
						query: {
							deviceId: this.zdeviceId,
							deviceNo: this.deviceNo,
							numIndex: i.id,

						}
					})
				}


			},

			async getlingquFn(i) {
				console.log('22222', i);
				const getss = await getMyMeal({
					deviceId: this.zdeviceId
				})
				if (!getss.data) {
					this.toast('请先购买套餐再领取')
					return false
				}
				const res = await APIreceive({
					// couponId: i.id,
					// code: i.putType == 2 ? i.code : '',
					agentId: this.agentId,
					activityId: i.activityId,
					ruleId: i.ruleId,
					code: '',
				})
				this.toast(res.code == 200 ? '领取成功' : '领取失败')
				setTimeout(() => {
					this.init()
				}, 1000)

			},

		}
	}
</script>

<style lang="scss" scoped>
	.one {
		margin-bottom: 90upx;
	}

	.oneTitle {
		font-size: 36upx;
		font-weight: 700;
		margin-bottom: 20upx;
		color: #777;
	}

	.twoTitle {
		color: red;
	}

	.threeTitle {
		color: green;
	}

	.tables {
		min-width: 90%;
		// display: flex;
		// justify-content: center;
	}

	u-tr {
		// display: flex;
		// justify-content: center;
		// align-items: center;
		// border: 0.5upx solid #aaa;
		font-size: 24upx !important;

	}

	.u-tr {
		text-align: center;
	}

	// .trth {
	// 	background-color: aqua !important;

	// }

	// .twoTrth {
	// 	background-color: blue;

	// }

	.u-th {
		// border: 0.5upx solid #aaa;
		padding-bottom: 10upx;
		padding-top: 10upx;
		text-align: center;
		min-height: 60upx;
		min-width: 13%;
	}

	.u-td {
		// border: 0.5upx solid #aaa;

		padding-bottom: 10upx;
		padding-top: 10upx;
		min-width: 13%;
		min-height: 70upx;
		text-align: center;
		// line-height: 70upx;
		word-break: normal;
		/* 规定段落中的文本不进行换行： */
		white-space: nowrap;
		/* 内容会被修剪，并且其余内容是不可见的。 */
		overflow: hidden;
		/* 显示省略符号来代表被修剪的文本。 */
		text-overflow: ellipsis;

	}

	.aa {
		min-width: 210upx !important;
	}

	.qq {
		min-width: 130upx !important;
	}

	.zz {
		min-width: 210upx !important;
	}

	.ww {
		min-width: 120upx !important;
	}

	.ss {
		min-width: 114upx !important;
	}

	.xx {
		min-width: 160upx !important;
	}

	.green {
		font-weight: 700;

		color: red !important;
		// background-color: aqua;
	}

	.greens {
		color: green;
	}

	.reds {
		color: red;
	}

	.blues {
		color: blue;
	}

	.qing {
		color: #ef8200;
	}

	.slot-content {
		font-size: 28rpx;
		color: $u-content-color;
		padding-left: 30rpx;
		margin-top: 16upx;
		line-height: 50upx;
		margin-bottom: 20upx;
	}

	.textwrap {

		word-break: break-all !important;
	}
</style>